// getSuggestion
import { getSearch, getSuggestion, TSearch, TSuggestion } from '@/api'
import { getStorage, removeStorage, setStorage } from '@/utils/loaclStorage'
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'
export const HISTORY_KEY = 'history'
// 获取联想
export const getSuggestionAction = createAsyncThunk(
  'search/getSuggestion',
  async (q: string) => {
    try {
      const res = await getSuggestion(q)
      return res.data.data
    } catch (error) {}
  }
)

// 获取搜索结果
export const getSearchAction = createAsyncThunk(
  'search/getSearch',
  async (q: string) => {
    try {
      const res = await getSearch(q)
      return res.data.data
    } catch (error) {}
  }
)

// 初始值类型
export interface ISuggestion {
  suggestion: string[]
  histories: string[]
  searchs: TSearch
}

// 初始值
const initialState: ISuggestion = {
  suggestion: [],
  histories: getStorage(HISTORY_KEY),
  searchs: {
    page: 1,
    per_page: 10,
    results: [],
    total_count: 0
  }
}

export const searchSlice = createSlice({
  name: 'search',
  initialState,
  reducers: {
    // 清除建议
    removeSuggestionAction (state) {
      state.suggestion = []
    },
    // 历史记录
    setHistoryAction (state, action: PayloadAction<string>) {
      // 缓存历史
      let histories = state.histories
      // 新历史
      let newHistoies: string[]
      // 缓存有历史记录
      if (histories) {
        newHistoies = Array.from(new Set([action.payload, ...histories]))
        // 大于10条
        if (newHistoies.length > 10) {
          // 删除最后一条
          newHistoies.splice(newHistoies.length - 1, 1)
        }
      } else {
        // 为null
        newHistoies = [action.payload]
      }
      // 存缓存，redux
      state.histories = newHistoies
      setStorage(HISTORY_KEY, newHistoies)
    },
    // 清除全部历史记录
    removeAllHistoryAction (state) {
      removeStorage(HISTORY_KEY)
      state.histories = []
    },
    // 清除个别历史记录
    removeHistoryAction (state, action: PayloadAction<string>) {
      state.histories = state.histories.filter(item => item !== action.payload)
      setStorage(HISTORY_KEY, state.histories)
    }
  },
  extraReducers: {
    // 获取联想成功
    [getSuggestionAction.fulfilled.type]: (
      state,
      action: PayloadAction<TSuggestion>
    ) => {
      const { options } = action.payload
      if (options[0] === null) {
        state.suggestion = []
      } else {
        state.suggestion = options as string[]
      }
    },
    // 搜索结果成功
    [getSearchAction.fulfilled.type]: (
      state,
      action: PayloadAction<TSearch>
    ) => {
      state.searchs = action.payload
    }
  }
})
// Action creators are generated for each case reducer function
export const {
  removeSuggestionAction,
  setHistoryAction,
  removeAllHistoryAction,
  removeHistoryAction
} = searchSlice.actions

export default searchSlice.reducer
